<template>
  <!-- AdminEditBusinessCard 管理员编辑指定单位的名片 -->
  <PageContainer>
    <view class="editbusiness-container">
      <Header
        title="编辑单位主页"
        :is-box-shadow="false"
        :enable-navigate-back-options="backOptions"
      />
      <Box :content-p-top="30">
        <ElegantDemeanour v-model="imgList" :is-edit="true" :card-type="ApplyTypeEnum.UNIT" />
        <BusinessCardInfo v-model="businessCardInfo" @add-logo="addLogo" @del-logo="delLogo" />
      </Box>
      <Box title="主营业务">
        <FormHonor
          v-model="mainBusinessList"
          label="主营业务"
          :tag-flex="true"
          :input-maxlength="10"
          placeholder="例：房地产开发、金融服务、汽车销售、服装生产"
        />
      </Box>
      <Box title="社会荣誉/职务">
        <FormHonor
          v-model="honorList"
          :tag-flex="true"
          label="社会荣誉/职务"
          placeholder="例：XX会长单位、XX示范企业、XX驰名品牌、XX高新企业"
        />
      </Box>
      <Box title="成员">
        <view class="member-temp">
          <MemberList v-model="memberData" :is-to-details="true" />
          <TButton
            text="添加"
            icon="&#xe61f;"
            :customStyle="{
              backgroundColor: '#f5f5f5',
              border: '2rpx dashed #dddddd',
              color: '#808080',
            }"
            @click="toSelectMembers"
          />
        </view>
      </Box>
      <Box title="简介">
        <CuttingLine :margin-top="0" />
        <UploadVideo :isEdit="true" v-model="videoInfo" />
        <CuttingLine />
        <CardComHeader title="电子文档" :des="`请上传${fileDefaultSize.doc}M以内文档文件`" />
        <FormUploadFile v-if="cardDetails" v-model="document" :limit="9" media-type="doc" />
        <CuttingLine />
        <Introduction
          v-model="introduce"
          placeholder="文化、品牌、产品、服务、优势等介绍"
          :isEdit="true"
          :card-type="ApplyTypeEnum.UNIT"
        />
      </Box>
      <TButtonGroup>
        <TButton class="gutter-btn" text="取消" custom-class="cardBlackBtn" @click="cancel" />
        <TButton class="gutter-btn" text="保存" custom-class="cardBtn" @click="submit" />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /**  AdminEditBusinessCard 管理员编辑指定单位的名片 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import Header from '@/components/Header/index.vue';
  import { ref, unref, watch } from 'vue';
  import { navigateTo, onLoad } from '@/router';
  import { editUnitCardDetails, orgBusinessCardCompany } from '@/api/card';
  import { type EditUnitCardDetailsData, type UnitCardDetailsResult } from '@/api/card/types';
  import ElegantDemeanour from '../components/elegantDemeanour/index.vue';
  import { ApplyTypeEnum } from '@/enums/membershipEnum';
  import Box from '../components/box/index.vue';
  import FormHonor from '@/components/Form/components/FormHonor.vue';
  import UploadVideo from '../components/uploadVideo/index.vue';
  import CuttingLine from '../components/cuttingLine/index.vue';
  import Introduction from '../components/introduction/index.vue';
  import MemberList from './components/memberList.vue';
  import BusinessCardInfo, { type BusinessCardInfoType } from './components/BusinessCardInfo.vue';
  import { Toast } from '@/utils';
  import { useUpload } from '@/hooks/core/useUpload';
  import { type IMemberItem } from '@/api/mine/types';
  import { useBackBeforeUnload, type UseNavigateBackOptions } from '@/hooks/core/useNavigateBack';
  import CardComHeader from '../components/cardComHeader/index.vue';
  import FormUploadFile from '@/components/Form/components/upload/FormUploadFile.vue';
  import { isArrayString } from '@/utils/is';
  import { fileDefaultSize } from '@/hooks/core/useUpload';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import type { EditBusinessCard } from '@/router/types/modules';
  import PrivacyPopup from '@/components/PrivacyPopup/index.vue';

  const useUser = useUserStoreWithOut();

  let callback: EditBusinessCard['callback'];

  const backOptions = ref<UseNavigateBackOptions>({
    enableBeforeUnload: true,
    showModalOptions: {
      content: '确认返回',
    },
  });

  const { interceptNavigateBack, UniNavigateBack } = useBackBeforeUnload(backOptions.value);

  const cardDetails = ref<UnitCardDetailsResult>();

  const businessCardInfo = ref<BusinessCardInfoType>({
    name: '',
    address: '',
    officeTel: '',
    logo: '',
  });

  const { result, chooseFile, delResultItem } = useUpload({
    count: 1,
    isCrop: true,
    cropOptions: {
      width: 400,
      height: 400,
    },
  });
  watch(
    result,
    (val) => {
      const item = val[0];
      if (item && item.isSuccess && !isSubmitLoading.value) {
        businessCardInfo.value.logo = item.filePath as string;
      }
    },
    { deep: true },
  );

  function addLogo() {
    chooseFile({ mediaType: 'image' });
  }
  function delLogo() {
    delResultItem(0);
    businessCardInfo.value.logo = '';
  }

  const imgList = ref<string[]>([]);
  const mainBusinessList = ref<string[]>([]);
  const honorList = ref<string[]>([]);
  const videoInfo = ref({
    tempFilePath: '',
    thumbTempFilePath: '',
  });

  const introduce = ref<string>('');

  const document = ref<string[]>();

  const memberData = ref<IMemberItem[]>([]);
  function toSelectMembers() {
    navigateTo({
      name: 'selectShowMembers',
      options: {
        cocId: unref(cardDetails)?.cocId,
        selectedMembers: memberData.value,
        submit: (members) => {
          memberData.value = members;
        },
      },
    });
  }

  function __init(data: UnitCardDetailsResult) {
    if (data) {
      cardDetails.value = data;
      businessCardInfo.value = {
        name: data.name,
        address: data.address,
        officeTel: data.officeTel,
        logo: data.logo,
      };
      imgList.value = data.imgList || [];
      mainBusinessList.value = data.mainBusinessList;
      honorList.value = data.honorList;
      videoInfo.value.tempFilePath = data.video ?? '';
      videoInfo.value.thumbTempFilePath = data.videoCover ?? '';
      introduce.value = data.memberDetails;
      memberData.value = data.leadingMemberVoList;
      if (data.document) {
        if (isArrayString(data.document)) {
          const arr = JSON.parse(data.document) as string[];
          document.value = arr.map((v) => v);
        } else {
          document.value = [JSON.stringify({ name: data.documentName, url: data.document })];
        }
      }
    } else {
      document.value = [];
    }
  }

  const isSubmitLoading = ref(false);
  const submit = () => {
    const info = cardDetails.value;
    if (!info) return;
    if (!businessCardInfo.value.name) return Toast('名称不能为空', 'none', 1500);
    if (isSubmitLoading.value) return;
    isSubmitLoading.value = true;
    const data: EditUnitCardDetailsData = {
      ...unref(businessCardInfo),
      imgList: unref(imgList),
      honorList: unref(honorList),
      mainBusinessList: unref(mainBusinessList),
      memberDetails: unref(introduce),
      videoCover: videoInfo.value.thumbTempFilePath,
      video: videoInfo.value.tempFilePath,
      document: JSON.stringify(unref(document)),
      id: info.id,
      cocId: info.cocId,
      leaderIdList: memberData.value.map((v) => v.id),
    };
    editUnitCardDetails(data).then((r) => {
      useUser.setUnitList();
      callback?.();
      UniNavigateBack();
    });
  };

  function cancel() {
    interceptNavigateBack();
  }

  onLoad<'AdminEditBusinessCard'>(async (op) => {
    callback = op.callback;
    const id = op.id;
    const data = await orgBusinessCardCompany(id);
    __init(data);
  });
</script>
<style lang="scss">
  .editbusiness-container {
    .business-card-info,
    .upload-popup {
      .uni-easyinput {
        text-align: right !important;
      }
    }
  }
  .edit-container .uni-easyinput__content-textarea {
    max-height: 600rpx;
  }
</style>
<style lang="scss" scoped>
  .editbusiness-container {
    .form-view {
      margin-top: 10rpx;
      padding-bottom: 30rpx;
    }
  }
</style>
